首页 > 解决方案 > 函数重定义:const参数

问题描述

1. 在全球范围内,这给出了error: redefinition of 'f'

#include <iostream> 
using namespace std; 
  
void f(int x) { cout << "f" << endl; }
void f(const int x) { cout << "f (const)" << endl; } // error: redefinition of 'f'
int main() { } 

2. 定义两个复制构造函数(一个带有const,另一个不带)编译

#include <iostream> 
using namespace std; 
  
class Foo { 
public: 
    Foo(const Foo&) { cout << "copy (const)" << endl; }
    Foo(Foo&) { cout << "copy" << endl; }
}; 

int main() { } 

问题

  1. 为什么 #1 是重定义错误,而 #2 不是?
  2. 对于第二个示例,是否有定义两个复制构造函数(一个有const另一个没有)的用例?

标签: c++copy-constructorredefinition

解决方案


两者有本质区别。

一个是 和 之间的过intconst int。它是一种价值类型。调用者没有语义差异,效果const只影响函数体。

void f(int);

int a = 1;
const int b = 2;

f(a); // must copy the int value into the argument
f(b); // same thing.

另一个是 const 与可变引用。它对调用者有所不同。

void f(int&);
void f(const int&);

int a = 1;
const int b = 2;

f(a); // could call f(int&) or f(int const&), but the mutable is a more closely match
f(b); // can only call f(int const&);

由于它是通过引用传递的,因此函数调用者的常量很重要。试图通过引用改变 const 对象的函数必须是无效的,并且默认情况下应将非 const 对象传递给非 const 重载。

只有价值观,这根本不重要。它是一个新对象。无论限定符是什么,它对调用者都没有意义,因此它不应该关心,因为它只影响实现。

您甚至可以仅在需要时在定义中添加 const,因为它声明了相同的函数:

void f(int);

int main() {
    f(1);
}

void f(const int a) {
    std::cout << "hello " << a << std::endl;
}

活生生的例子


至于你的第二个问题,我想说的是,由于添加了右值引用,因此几乎不需要复制构造函数来获取可变引用。

例如,std::auto_ptr曾经有一个构造函数采用可变引用来转移所有权,但它产生了各种各样的问题。但它已被完全取代std::unique_ptr,它使用右值引用来转移所有权。

右值引用确保您不关心复制对象的完整性,并且可以从中窃取资源。


推荐阅读