V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
AzadCypress
V2EX  ›  问与答

问一个 C++构造函数中括号的问题

  •  
  •   AzadCypress · Oct 30, 2021 · 1318 views
    This topic created in 1641 days ago, the information mentioned may be changed or developed.

    代码是 c++Primer 上的一个例子修改来的

    用 g++ 的话第 20 行通不过编译;用 visual studio 20 和 21 行都通不过编译

    是因为这里面有什么未定义行为吗? (DebugDelete(cout));DebugDelete(cout); 区别在哪里?

    有个发现就是在这里 DebugDelete(cout)行为是类似于 int (a)的,编译器会认为这里定义了一个变量 cout 。

    还有就是

    DebugDelete(cout).operator()(p);  //可以运行
    DebugDelete(cout)(p) ;   //报错
    

    image.png

    #include <iostream>
    using namespace std;
    
    class DebugDelete {
    public:
    	DebugDelete(std::ostream& o) :os(o) {
    	}
    	template<typename T> void operator()(T* p) {
    		delete(p);
    		os << "deleted\n";
    	}
    private:
    	std::ostream& os;
    };
    
    int main() {
    	int* p = new int(10);
    	(DebugDelete(cout));
    	DebugDelete{ cout };
    	DebugDelete(cout);   // 
    	DebugDelete(std::cout);
    }
    

    编辑的过程中想到这个例子应该可以抽象成这样,所以这个其实可能是变量声明优先于临时对象构造函数的问题?关于这个有没有详细解释?

    class A {
    public:
    	A(int n){}
    };
    int n = 10;
    int main() {
    	(A(n));   // ok
    	A(n);     // error
    }
    
    2 replies    2021-10-30 04:31:25 +08:00
    geelaw
        1
    geelaw  
       Oct 30, 2021 via iPhone   ❤️ 2
    https://stackoverflow.com/questions/45991094/which-part-of-the-c-standard-allow-to-declare-variable-in-parenthesis

    另外声明语句优先于表达式语句也会造成传统的 most vexing parse 局面。

    你的每对报错 /可以编译的例子里,都是一个只能解读为表达式语句,另一个既可以解读为表达式语句,又可以解读为声明语句,然后声明语句优先,但是无效。
    c0xt30a
        2
    c0xt30a  
       Oct 30, 2021
    `DebugDelete(cout); ` 在这里其实相当于 `DebugDelete cout; ` 那个括号加不加都一样。 然后编译器发现你的 DebugDelete 没有 default ctor ,于是报错。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   997 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 22:25 · PVG 06:25 · LAX 15:25 · JFK 18:25
    ♥ Do have faith in what you're doing.