简体   繁体   中英

Passing std vector as reference: no matching function to call

I can't see what's wrong with my code. I have a an std::vector which is a private member of my class Foo. It is not declared as const, even when the error the compiler gives suggests so.

(At Foo.h)

private:
std::vector<std::string> tableBackup;

I'm calling a function (from Foo.cpp):

BackupTable(this->tableBackup);

This method is into DatabaseLoad.cpp and .h:

public:
void BackupTable(std::vector<std::string> &tableBackup);

Defined as:

void DatabaseLoad::BackupTable(std::vector<std::string> &tableBackup){
//whatever...
}

I'm getting the following error when I call the method from Foo.cpp:

No matching function for call to 'DatabaseLoad::BackupTable(const std::vector<std::basic_string<char> > &)'

What's the problem? Currently using C++11, but I guess this has nothing to do with that.

You are calling the BackupTable function in a context where the DatabaseLoad object is const -qualified, therefore the compiler is expecting a call to a const -reference.

If you are not planning on modifying the vector, you should declare the function as:

void BackupTable(const std::vector<std::string>& tableBackup);

我猜你是从Foo类的const方法调用BackupTable的

You seem to be calling BackupTable(this->tableBackup); inside a member function which is qualified as const . This means that this is of type const Whatever* , and thus all data members are implicitly const -qualified inside this member function as well. So they cannot be bound to a non- const reference.

You have two sane options:

  1. If BackupTable does not modify its argument, it should accept it as const & instead of just & .

  2. If it does modify its argument, it means the calling function modifies its this object, so it should not be marked as const .

A third (far less likely) option is that tableBackup is actually an implementation details of your class and the fact that it changes does not affect the "logical const ness" of the class. If that is so, you can mark it as mutable (that way, even const functions will be able to modify it). At the same time, you must introduce some form of synchronisation mechanism (eg a mutex) whenever you access the mutable tableBackup (or any mutable member). The reason is that all of the standard library expects const operations to be thread-safe. An emerging idiom for this is adding a private member like this:

mutable std::mutex mutables;

And locking mutables whenever you access (even just for reading!) a mutable member.

I think that 'this' is const in ' BackupTable(this->tableBackup);'. You call the ' BackupTable' in a 'Foo() const' function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM