C++ 对象声明和无默认构造函数(用户声明或隐式声明)

C++ object declaration and no default constructor (user-declared or implicitly-declared)

如果我有

class Something
{
public:
    Something(int whatever) : whatever_(whatever) {}
private:
    int whatever_;
}

那么当我在堆栈上创建一个对象时会发生什么

Something something;

因为没有默认构造函数?

在符合标准的编译器上,您会遇到编译错误。

以下代码:

class Something
{
public:
    Something(int whatever) : whatever_(whatever) {}
private:
    int whatever_;
};

Something something;

用gcc8.2编译时出现如下编译错误:

<source>:9:11: error: no matching function for call to 'Something::Something()' 
 Something something;
           ^~~~~~~~~    
<source>:4:5: note: candidate: 'Something::Something(int)'    
     Something(int whatever) : whatever_(whatever) {}    
     ^~~~~~~~~    
<source>:4:5: note:   candidate expects 1 argument, 0 provided    
<source>:1:7: note: candidate: 'constexpr Something::Something(const Something&)'    
 class Something    
       ^~~~~~~~~    
<source>:1:7: note:   candidate expects 1 argument, 0 provided    
<source>:1:7: note: candidate: 'constexpr Something::Something(Something&&)'    
<source>:1:7: note:   candidate expects 1 argument, 0 provided    
Compiler returned: 1

可在 godbolt.

获取现场示例